#! /bin/sh

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin


PWD_dir=`pwd`
SRC_parentdir=/usr/local/src
SRC_tgz=memcached-1.4.16.tar.gz
SRC_dir=`basename $SRC_tgz .tar.gz`
SRC_name=memcached

DEST_dir=/tmp/$SRC_dir

RPM_version='1.4.16.dt2.el6'

[ -d $PWD_dir/scripts ] || mkdir -p $PWD_dir/scripts
[ -d $DEST_dir ] || mkdir -p $DEST_dir

rpm -q make || yum -y install make
rpm -q gcc || yum -y install gcc
rpm -q rubygems || yum -y install rubygems ruby-devel
rpm -q libevent-devel || yum -y install libevent-devel
rpm -q rpm-build || yum -y install rpm-build


if [ ! -x /usr/bin/fpm ]; then
    echo "fpm were not installed"
    gem install fpm --source https://ruby.taobao.org/
else
    echo "fpm have installed"
fi


cd $SRC_parentdir
# if [ -f $SRC_tgz ]; then
if [ ! -f $SRC_tgz ]; then
    curl -LSso $SRC_tgz http://memcached.org/files/$SRC_tgz
    tar zxf $SRC_tgz
    cd $SRC_dir
    ./configure --prefix=/usr
    make
    make install DESTDIR=$DEST_dir
    cp -f scripts/memcached.sysv $PWD_dir/scripts/memcached
    cp -f scripts/memcached-tool $DEST_dir/usr/bin/
fi

#######
cd $PWD_dir
sed -i '/^USER/s/nobody/memcached/' scripts/memcached

fpm -s dir -t rpm -v $RPM_version --epoch 2 \
    -n $SRC_name \
    -d 'libevent-devel >= 1.4.13-4' \
    --rpm-init scripts/memcached \
    --before-install scripts/beforeinstall \
    --after-install scripts/afterinstall \
    --before-remove scripts/beforeuninstall \
    --after-remove scripts/afteruninstall \
    -C $DEST_dir .


#rm -rf $DEST_dir
##
